package com.cmdi.opensite.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmdi.opensite.entity.Comment;
import com.cmdi.opensite.mapper.CommentMapper;
import com.cmdi.opensite.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 评价服务实现类
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    
    @Autowired
    private CommentMapper commentMapper;
    
    @Override
    public boolean addComment(Comment comment) {
        // 检查是否已评价
        if (hasCommented(comment.getActivityId(), comment.getUserId())) {
            return false;
        }
        return save(comment);
    }
    
    @Override
    public boolean deleteComment(Long id, Long userId) {
        Comment comment = getById(id);
        if (comment != null && comment.getUserId().equals(userId)) {
            return removeById(id);
        }
        return false;
    }
    
    @Override
    public IPage<Comment> getActivityComments(IPage<Comment> page, Long activityId) {
        return commentMapper.selectActivityComments(page, activityId);
    }
    
    @Override
    public boolean hasCommented(Long activityId, Long userId) {
        return commentMapper.findByActivityIdAndUserId(activityId, userId) != null;
    }
    
    @Override
    public double getAverageScore(Long activityId) {
        Double score = commentMapper.calculateAverageScore(activityId);
        return score != null ? score : 0.0;
    }
    
    @Override
    public int getCommentCount(Long activityId) {
        return commentMapper.countCommentsByActivityId(activityId);
    }
}